package day22;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class day22 {
    public static void main(String[] args) throws InterruptedException {
        BankAccount from=new BankAccount(2000);
        BankAccount to=new BankAccount(1000);
        TransferTask tt=new TransferTask(from,to,1000);
//        Thread t1=new Thread(tt);
//        Thread t2=new Thread(tt);
//        Thread t3=new Thread(tt);
//        Thread t4=new Thread(tt);
//        Thread t5=new Thread(tt);

//        t1.start();
//        t2.start();
//        t3.start();
//        t4.start();
//        t5.start();

//        t1.join();
//        t2.join();
//        t3.join();
//        t4.join();
//        t5.join();

        //利用线程池
        ExecutorService pool= Executors.newCachedThreadPool();
        for (int i=0;i<5;i++){
            pool.execute(tt);
        }
        pool.shutdown();
        //等线程池都走完了才会执行
        while (true){
            //等待线程池关闭，并且线程里面的任务都结束
            if (pool.isTerminated()){
                System.out.println(from.balance);
                System.out.println(to.balance);
                break;
            }
        }

    }
}

class BankAccount{
    double balance;//余额
    public BankAccount(double balance){
        this.balance=balance;
    }
    //存钱
    public synchronized void deposit(double amount){
        String name=Thread.currentThread().getName();
        balance+=amount;
        System.out.println(name+"成功存储了:"+amount+",余额:"+balance);
    }
    //取钱
    public synchronized boolean withDraw(double amount){
        String name=Thread.currentThread().getName();
        if(balance>=amount){
            balance-=amount;
            System.out.println(name+"取出了:"+amount+",余额:"+balance);
            return true;
        }else {
            return false;
        }
    }
}

class TransferTask implements Runnable{
    BankAccount from; //转出账号
    BankAccount to; //转入账号
    double money;

    public TransferTask(BankAccount from, BankAccount to, double money) {
        this.from = from;
        this.to = to;
        this.money = money;
    }

    public void run() {
        //模拟转账功能？
        //（保证线程安全，A和B两个账号都必须控制数据同步）
        String name=Thread.currentThread().getName();
        synchronized (from){ //先取钱
            //如果余额充足，就可以先取钱
            if (from.withDraw(money)){
                synchronized (to){ //再给另一个账号加钱
                    to.deposit(money);
                    System.out.println(name+"转账成功！");
                }
            }else {
                System.out.println(name+"转账失败，余额不足！");
            }

        }

    }
}